<template>
    <span class="header-item">
        <div class="header">
            <img src="../images/LOGO1.png"
                 style="height: 100%">
            <div style="display: flex;">
                <div class="business-title">
                    <span>{{title}}</span>
                </div>
                <div class="counter-down"
                     v-if="mode === 'exam'">
                    <span id="countdownExam"></span>
                </div>
            </div>

            <span class="business-menu">
                <el-popover placement="bottom"
                            width="400"
                            :disabled="mode === 'exam'">
                    <span :class="menuItemClass"
                          slot="reference"
                          v-if="mode !== 'exam'">
                        <label>帮助提示</label>
                    </span>
                    <p>{{ step && step.description }}</p>
                    <h3 v-if="!step || !step.description">无帮助提示</h3>
                </el-popover>
                <span :class="menuItemClass"
                      v-if="mode !== 'exam'">
                    <label @click="showStepVideo">操作演示</label>
                </span>
                <el-popover placement="bottom"
                            width="400"
                            :disabled="mode === 'exam'">
                    <span :class="menuItemClass"
                          slot="reference"
                          v-if="mode !== 'exam'">
                        <label>风险提示</label>
                    </span>
                    <p>{{ step && step.risk }}</p>
                    <h3 v-if="!step || !step.risk">无风险提示</h3>
                </el-popover>
                <span :class="menuItemClass"
                      v-if="mode !== 'exam'">
                    <label @click="showBusinessListFn">业务列表</label>
                </span>
                <span :class="menuItemClass">
                    <label @click="confirm = true">
                        {{mode === 'exam' ? '结束考试' : '结束学习'}}
                    </label>
                </span>
            </span>
        </div>
        <el-dialog title="确定结束吗？"
                   :visible="confirm"
                   :modal="false"
                   width="50%"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   :before-close="() => { confirm = false } ">
            <span v-if="mode === 'study'">
                <h2>学习注意事项：</h2>
                <el-alert title="学习过程中如果主动结束业务则为提交当前业务学习结果！"
                          type="error"
                          :closable="false"
                          show-icon />
            </span>
            <span v-if="mode === 'exam'">
                <h2>考试注意事项：</h2>
                <el-alert title="按业务从上到下顺序进行依次考试"
                          type="warning"
                          :closable="false"
                          show-icon />
                <el-alert title="考试过程中切勿关闭或刷新浏览器，成绩不做记录！需要重新考试全部业务！"
                          type="error"
                          :closable="false"
                          show-icon />
                <el-alert title="考试过程中如果主动结束业务，则视为提交当前业务考试结果！"
                          type="error"
                          :closable="false"
                          show-icon />
            </span>
            <span slot="footer"
                  class="dialog-footer">
                <el-button type="text"
                           @click="confirm = false">取消</el-button>
                <el-button type="primary"
                           @click="end">确定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="操作演示"
                   :visible="showVideo"
                   :modal="false"
                   width="80%"
                   :close-on-click-modal="false"
                   @close="showVideo = false">
            <video v-if="showVideo && videoUrl"
                   :src="videoUrl"
                   autoplay
                   style="width: 100%"
                   controls />
            <h3 v-if="!videoUrl">无操作演示</h3>
        </el-dialog>
        <el-dialog title="考试未开始，距离开始时间"
                   width="50%"
                   :visible="showBusinessList && validateExamStatus == 'start_counter'"
                   :modal="false"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   :show-close="mode === 'exam' ? false : true"
                   @opened="execExamStartTimeCounter()">
            <div class="counter-down-exam-start"
                 v-if="mode === 'exam' && validateExamStatus == 'start_counter'">
                <span id="countdownExamStart">00:00:00</span>
            </div>
            <span v-if="mode === 'exam'">
                <h3>考试注意事项：</h3>
                <el-alert title="按业务从上到下顺序进行依次考试"
                          type="warning"
                          :closable="false"
                          show-icon />
                <el-alert title="考试过程中切勿关闭或刷新浏览器，成绩不做记录！需要重新考试全部业务！"
                          type="error"
                          :closable="false"
                          show-icon />
                <el-alert title="考试过程中如果主动结束业务，则视为提交当前业务考试结果！"
                          type="error"
                          :closable="false"
                          show-icon />
            </span>
            <div class="business-group"
                 v-for="group in businessGroups"
                 :key="group.name">
                <h3>{{ group.name }}</h3>
                <ul class="business-list">
                    <li v-for="item in group.items"
                        :key="item.id"
                        :class="{ active: item.id === businessTemplate.id }"
                        :style="businessListStyle">
                        <span @click="changeBusinessTemplate(item.id)"
                              style="cursor: pointer">{{ item.name }}</span>
                    </li>
                </ul>
            </div>
        </el-dialog>
        <el-dialog title="业务列表"
                   width="50%"
                   :visible="showBusinessList && (mode !== 'exam' || validateExamStatus == 'exam_counter')"
                   :modal="false"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   :show-close="mode === 'exam' ? false : true"
                   @close="mode !== 'exam' ? showBusinessList = false : undefined">
            <span v-if="mode === 'exam'">
                <h3>考试注意事项：</h3>
                <el-alert title="按业务从上到下顺序进行依次考试"
                          type="warning"
                          :closable="false"
                          show-icon />
                <el-alert title="考试过程中切勿关闭或刷新浏览器，成绩不做记录！需要重新考试全部业务！"
                          type="error"
                          :closable="false"
                          show-icon />
                <el-alert title="考试过程中如果主动结束业务，则视为提交当前业务考试结果！"
                          type="error"
                          :closable="false"
                          show-icon />
            </span>
            <div class="business-group"
                 v-for="group in businessGroups"
                 :key="group.name">
                <h3>{{ group.name }}</h3>
                <ul class="business-list">
                    <li v-for="item in group.items"
                        :key="item.id"
                        :class="{ active: item.id === businessTemplate.id }"
                        :style="businessListStyle">
                        <span @click="changeBusinessTemplate(item.id)"
                              style="cursor: pointer">{{ item.name }}</span>
                        <span v-if="mode === 'study' && item.id === businessTemplate.id">
                            <el-button size="mini"
                                       type="text"
                                       v-if="item.businessVideoUrl && item.businessVideoUrl !== '#'"
                                       @click="showBusinessVideo(item)">查看视频</el-button>
                            <el-button type="primary"
                                       size="mini"
                                       @click="changeBusinessTemplate(item.id)">开始学习</el-button>
                        </span>
                    </li>
                </ul>
            </div>
            <div style="width: 100%; text-align: right">
                <el-button v-if="mode === 'exam'"
                           type="primary"
                           size="mini"
                           @click="start">开始考试</el-button>
            </div>
        </el-dialog>
    </span>
</template>
<script>
    import { mapState, mapGetters } from "vuex";
    import { Timer } from "easytimer.js";
    import moment from "moment";

    export default {
        name: "header-item",
        props: ["title", "step", "mode"],
        data() {
            return {
                showBusinessList: false,
                confirm: false,
                showVideo: false,
                showEndDialog: false,
                videoUrl: null,
                validateExamStatus: ""
            };
        },
        computed: {
            menuItemClass() {
                // return { 'menu-item': true, diabled: this.mode === 'exam' }
                return { "menu-item": true };
            },
            ...mapState("course", ["businessTemplate", "businessTemplates"]),
            ...mapGetters(["examMinutes", "examStartTime"]),
            businessListStyle() {
                return {
                    justifyContent:
                        this.mode === "study" ? "space-between" : "center"
                };
            },
            businessGroups() {
                const businessTemplates =
                    !this.businessTemplates || this.businessTemplates.length < 1
                        ? [this.businessTemplate]
                        : this.businessTemplates;
                return businessTemplates.reduce((last, curr) => {
                    const group = last.find(g => g.name === curr.classFullPathJson);
                    if (group) {
                        group.items.push(curr);
                    } else {
                        last.push({ name: curr.classFullPathJson, items: [curr] });
                    }
                    return last;
                }, []);
            }
        },
        created() {
            if (
                this.mode !== "edit" &&
                this.businessTemplates &&
                this.businessTemplates.length > 0
            ) {
                this.showBusinessList = true;
            }
            this.$on("startExam", this.execExamTimeCounter);
        },
        mounted() {
            let self = this;
            this.mode === "exam" &&
                setTimeout(() => {
                    const diffFromExamStartTime = self.computeDiffFromExamStartBySecs();
                    if (diffFromExamStartTime < 0) {
                        // 判定是否考试时间未到，进行考试开始倒计时弹框
                        self.validateExamStatus = "start_counter";
                        return;
                    } else if (
                        diffFromExamStartTime >=
                        60 * Number(self.examMinutes)
                    ) {
                        // 判定是否考试超时，超时后弹框提示然后跳转到考试列表
                        self.validateExamStatus = "end_counter";
                        this.$emit("end", "invalid_exam");
                        return;
                    } else {
                        self.validateExamStatus = "exam_counter";
                    }
                    self.$emit("startExam");
                }, 0);
        },
        methods: {
            computeDiffFromExamStartBySecs() {
                const nowDate = moment();
                return nowDate.diff(moment(this.examStartTime), "second");
            },
            execExamStartTimeCounter() {
                let self = this;
                const diffFromExamStartTime = self.computeDiffFromExamStartBySecs();
                const timer = new Timer();
                let countdown = document.getElementById("countdownExamStart");
                if (countdown) {
                    timer.start({
                        countdown: true,
                        startValues: {
                            seconds: -diffFromExamStartTime
                        }
                    });
                    countdown.innerHTML = timer.getTimeValues().toString();
                    timer.addEventListener("secondsUpdated", function(e) {
                        countdown.innerHTML = timer.getTimeValues().toString();
                    });
                    timer.addEventListener("targetAchieved", function(e) {
                        self.validateExamStatus = "exam_counter";
                        self.$emit("startExam");
                    });
                }
            },
            execExamTimeCounter() {
                let self = this;
                const diffFromExamStartTime = self.computeDiffFromExamStartBySecs();
                if (diffFromExamStartTime < 0) {
                    return;
                }
                const timer = new Timer();
                let countdown = document.getElementById("countdownExam");
                if (countdown) {
                    timer.start({
                        countdown: true,
                        startValues: {
                            seconds:
                                Number(self.examMinutes) * 60 -
                                diffFromExamStartTime
                        }
                    });
                    countdown.innerHTML =
                        "考试时间剩余: " + timer.getTimeValues().toString();
                    timer.addEventListener("secondsUpdated", function(e) {
                        countdown.innerHTML =
                            "考试时间剩余: " + timer.getTimeValues().toString();
                    });
                    timer.addEventListener("targetAchieved", function(e) {
                        //提交超时事件
                        self.$emit("end");
                    });
                }
            },
            showBusinessListFn() {
                if (this.mode !== "exam") {
                    this.showBusinessList = true;
                }
            },
            showBusinessVideo(business) {
                this.showBusinessList = false;
                this.showVideo = true;
                this.videoUrl = business.businessVideoUrl;
            },
            showStepVideo() {
                if (this.mode !== "exam") {
                    this.showVideo = true;
                    this.videoUrl = this.step.video;
                }
            },
            changeBusinessTemplate(id) {
                if (this.mode === "study") {
                    this.$emit("change", id);
                    this.start();
                }
            },
            start() {
                this.$emit("start");
                this.showBusinessList = false;
            },
            end() {
                this.confirm = false;
                this.$emit("end");
            }
        }
    };
</script>
<style lang="less">
.header-item {
    h2 {
        margin: 0px !important;
    }

    .el-alert {
        margin-top: 10px !important;
    }

    .el-alert__icon {
        font-size: 20px !important;
        width: 20px !important;
    }

    .el-alert__title {
        font-size: 14px !important;
        width: 14px !important;
    }
}

.header {
    position: absolute;
    z-index: 1;
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: space-between;
    background-color: white;
    box-shadow: 5px 5px 15px rgba(255, 105, 0, 0.5);
    clip-path: inset(0px 0px -15px 0px);

    .business-menu {
        font-size: 21px;
        line-height: 2.5;

        .menu-item {
            padding-right: 20px;

            label {
                cursor: pointer;
                padding: 4px 15px;
                border-radius: 25px;
                font-weight: 400;
                color: white;
                background-color: #ff6900;
            }

            &:hover {
                opacity: 0.6;
                transition: 0.3s;
            }

            &.diabled {
                opacity: 0.6;
            }
        }
    }
}

.business-title {
    margin: auto;

    span {
        font-size: 20px;
        padding: 7px 15px;
        border-radius: 8px;
        font-weight: 400;
        color: white;
        background-color: #ff6900;
    }
}

.counter-down-exam-start {
    display: flex;
    span {
        margin-left: auto;
        margin-right: auto;
        font-size: 32px;
        padding: 7px 15px;
        font-weight: 400;
        color: #ff6900;
    }
}

.counter-down {
    margin-top: 12px;
    span {
        font-size: 20px;
        padding: 7px 15px;
        font-weight: 400;
        color: #ff6900;
    }
}

.business-list {
    list-style-type: none;
    padding-inline-start: unset;

    li {
        display: flex;
        font-size: 16px;
        background-color: #eee;
        border-radius: 3px;
        padding: 8px;
        margin: 8px;
    }

    .active {
        color: #ff6900;
    }
}
</style>


